import React, { Component } from 'react'
import { withRouter } from "react-router-dom"
import { Modal, Button, Space } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import "./index.css"

// 导入请求定位和天气的ajax
import http from "../../api/tianqi"
// 导入获取时间的函数
import dateStr from "../../config/huoQuDate"

const { confirm } = Modal

class MyHeader extends Component {
  state = { city: '北京', reporttime: '2008-1-1 12:00:00', weather: '晴' }
  async componentDidMount() {
    try {
      // 获取城市编码
      const item1 = await http.get('/ip?key=7606b5b9ce88eda09c0bf1d98a6abf87')
      const { adcode } = item1.data
      // 根据城市编码查询天气
      const item2 = await http.get(`/weather/weatherInfo?city=${adcode}&key=7606b5b9ce88eda09c0bf1d98a6abf87`)
      const { lives } = item2.data
      const { city, weather } = lives[0]
      this.setState({ city, weather })
    } catch (err) {
      console.log('获取天气失败！')
    }
    // 获取时间
    this.setState({ reporttime: dateStr() })
    this.timer = setInterval(() => {
      this.setState({ reporttime: dateStr() })
    }, 1000)
  }
  componentWillUnmount() {
    // 清除定时器
    clearInterval(this.timer)
  }
  // 退出登录确定框
  showConfirm = () => {
    const onOk= () => {
      // 清空 localStorage ，清除用户信息
      localStorage.clear()
      // 跳转到登录页
      this.props.history.push('/login')
    }
    confirm({
      title: '确定退出吗?',
      icon: <ExclamationCircleOutlined />,
      content: '退出将要重新登录',
      okText: '确认',
      cancelText: '取消',
      // 确定按钮回调
      onOk
    })
  }
  render() {
    // 获取当前标题
    const { state } = this.props.location
    const title = state ? state.title : '首页'
    return (
      <div className="my-header">
        <div className="header-top">
          <span className="username">{ localStorage.getItem('grain_name') }</span>
          <Space>
            <Button type="primary" onClick={this.showConfirm}>退出</Button>
          </Space>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{this.state.reporttime}</span>
            <span>{this.state.city}</span>
            <span>{this.state.weather}</span>
          </div>
        </div>
      </div>
    )
  }
}

export default withRouter(MyHeader)
